package com.yurun.storageservice.tcc;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yurun.domain.Storage;
import com.yurun.storageservice.mapper.StorageMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author Xi Gao
 * @date 2020/9/13 13:54
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class StorageActionServiceImpl implements StorageActionService {
    @Resource
    private StorageMapper storageMapper;


    @Override
    public boolean reduceStock(BusinessActionContext context, String goodCode, Integer num) {
        //查看库存是否足够
        QueryWrapper<Storage> storageQueryWrapper = new QueryWrapper<>();
        storageQueryWrapper.eq("commodity_code", goodCode);
        Storage storage = storageMapper.selectOne(storageQueryWrapper);
        if (storage.getCount() < num) {
            log.info("库存不足");
            return false;
        }
        //执行减库存操作
        int i = storageMapper.updateAmountByGoodCode(goodCode, num);
        if (i > 0) {
            ResultHolder.setResult(getClass(), context.getXid(), "T");
            return true;
        } else {
            log.info("更新失败");
            return false;
        }
    }


    @Override
    public boolean mycommit(BusinessActionContext context) {
        log.info("storage=====commit--Start");
        if (ResultHolder.getResult(getClass(), context.getXid()) == null) {
            return true;
        }
        log.info("storage=====commit--End");
        ResultHolder.removeResult(getClass(), context.getXid());
        return false;
    }

    @Override
    public boolean myrollBack(BusinessActionContext context) {
        log.info("storage=====rollBack--Start");
        if (ResultHolder.getResult(getClass(), context.getXid()) == null) {
            return true;
        }
        String goodCode = (String) context.getActionContext("goodCode");
        Integer num = (Integer) context.getActionContext("num");
        storageMapper.updateAmountByGoodCode(goodCode, -num);
        //回退更新失败怎么办。。。。
        log.info("storage=====rollBack--End");
        ResultHolder.removeResult(getClass(), context.getXid());
        return true;
    }
}
